/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-09-12 11:06:48
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-24 11:36:23
 * @FilePath: /react18-vite-admin/src/router/Root.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useEffect, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, Navigate } from 'react-router-dom';
import Cookie from 'js-cookie';

// import NProgress from 'nprogress';
// import 'nprogress/nprogress.css';

import { useHttpInterceptor } from '@/service/app/useRequest';
import {
    useUser,
    useUserStore,
    usePermissionStore,
    findRelatedNodes,
    useAppStore
} from '@/store';
import LoadingPage from '@/components/ui/LoadingPage/LoadingPage';
import { useRoutesAndMenus } from '@/service/useRoutesAndMenus';
import { treeToArray } from '@/utils';

// 白名单路由
const whiteList = ['/login'];

let isUpdating = false;

const BeforeEach = (props: { children: ReactNode }) => {
    useHttpInterceptor();
    const { t } = useTranslation();
    const { pathname, search } = useLocation();
    const navigate = useNavigate();
    const { getMyInfo } = useUser();
    const { setActiveIds } = useAppStore((state) => state);
    const { updateRouterAndMenus } = useRoutesAndMenus();
    const { needUpdate, routes, redirectPaths } = usePermissionStore(
        (state) => state
    );
    const { token } = useUserStore((state) => state);

    // 设置网页标题
    let title = t('app.title');
    const routesList = treeToArray(routes);
    const len = routesList.length;
    treeToArray(routes).find((item) => {
        if (item.path === pathname && item.meta?.title) {
            title = item.meta?.title;
        }
    });
    for (let i = 0; i < len; i++) {
        const item = routesList[i];
        if (item.path === pathname) {
            if (item.meta?.title) {
                title = item.meta?.title;
            }
            break;
        }
    }
    // console.log('beforeeach', pathname, reactRouter?.routes, token, needUpdate);
    document.title = title;
    // const hasRouteAuth = (path: string, routes: AppRouteRecordRaw[]) => {
    //     const arr = treeToArray(routes);
    //     for (let i = 0; i < arr.length; i++) {
    //         const route = arr[i];
    //         if (path === route.path) {
    //             return true;
    //         }
    //     }
    //     return false;
    // };
    const setAppActiveIds = () => {
        const activeIds = findRelatedNodes(
            pathname,
            usePermissionStore.getState().menuTree
        ).map((item) => `${item.id}`);
        setActiveIds(activeIds);
    };

    const handleNeedUpdate = async () => {
        if (token) {
            try {
                if (isUpdating) return;
                isUpdating = true;
                console.log('getMyInfo');
                await getMyInfo();
                const menuTree = useUserStore.getState().menuTree;
                if (menuTree === undefined)
                    throw new Error('当前用户没有未分配菜单树');
                // setUserByMyInfo(res.data);
                updateRouterAndMenus(menuTree);
                // 设置cookie用于获取图片
                Cookie.set('token', token);
                // 设置当前激活菜单
                setAppActiveIds();
                // if (!hasRouteAuth(pathname, allRoutes)) {
                //     navigate('/');
                // }
            } catch (e) {
                console.log(e);
            } finally {
                isUpdating = false;
            }
        }
    };

    // 路由改变则设置激活菜单
    useEffect(() => {
        if (redirectPaths[pathname]) {
            navigate(redirectPaths[pathname] + search);
        }
        if (token === undefined) {
            navigate(
                `/login?redirect=${
                    pathname === '/login' ? '/' : pathname + search
                }`
            );
        }
        setAppActiveIds();
    }, [pathname]);

    if (whiteList.includes(pathname)) {
        return <>{props.children}</>;
    } else {
        if (token) {
            if (needUpdate) {
                // 更新路由操作
                handleNeedUpdate();
                return <LoadingPage />;
            }
            return <>{props.children}</>;
        }
    }
};

export default BeforeEach;
